#Region " Imports "

Imports System.Data
Imports BlazeApps.Library.Forum
Imports BlazeApps.Library.Resources

#End Region

Partial Class Usercontrols_Forum_Post
    Inherits UserControlBase

#Region " Enums, Memebers and Properties "

    Private ForumCheck As New ForumChecks
    Private DataPageLocal As New PagedDataSource

    Public Property sortCriteria() As String
        Get
            Return CStr(ViewState("sortCriteria"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortCriteria") = Value
        End Set
    End Property

    Public Property sortDir() As String
        Get
            Return CStr(ViewState("sortDir"))
        End Get

        Set(ByVal Value As String)
            ViewState("sortDir") = Value
        End Set
    End Property

    Protected Property BoardGuid() As Guid
        Get
            Return GetGuidFromVS("BoardID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("BoardID", value)
        End Set
    End Property

    Protected Property CategoryGuid() As Guid
        Get
            Return GetGuidFromVS("CategoryID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("CategoryID", value)
        End Set
    End Property

    Protected Property ForumGuid() As Guid
        Get
            Return GetGuidFromVS("ForumID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("ForumID", value)
        End Set
    End Property

    Protected Property TopicGuid() As Guid
        Get
            Return GetGuidFromVS("TopicID")
        End Get
        Set(ByVal value As Guid)
            ViewState.Add("TopicID", value)
        End Set
    End Property

    Protected Property BoardName() As String
        Get
            Return GetStringFromVS("BoardName")
        End Get
        Set(ByVal value As String)
            ViewState.Add("BoardName", value)
        End Set
    End Property

    Protected Property CategoryName() As String
        Get
            Return GetStringFromVS("CategoryName")
        End Get
        Set(ByVal value As String)
            ViewState.Add("CategoryName", value)
        End Set
    End Property

    Protected Property ForumName() As String
        Get
            Return GetStringFromVS("ForumName")
        End Get
        Set(ByVal value As String)
            ViewState.Add("ForumName", value)
        End Set
    End Property

    Protected Property TopicName() As String
        Get
            Return GetStringFromVS("TopicName")
        End Get
        Set(ByVal value As String)
            ViewState.Add("TopicName", value)
        End Set
    End Property

    Protected Property ForumLocked() As Boolean
        Get
            Return GetBooleanFromVS("Locked")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("Locked", value)
        End Set
    End Property

    Protected Property ForumModerated() As Boolean
        Get
            Return GetBooleanFromVS("ForumModerated")
        End Get
        Set(ByVal value As Boolean)
            ViewState.Add("ForumModerated", value)
        End Set
    End Property

#End Region

#Region " Page Events "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.MessageLabel = Me.uxMessagesLabel
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        SetPageTitle("Posts")

        If ShowItem(ForumGuid) = True Then

            GetQueryStringValues()
            'ConfigBaseEditorCtrls()

            If Me.Page.IsPostBack = False Then

                'BuildEditor(EditorPageType.ForumEditor)

                ForumModerated = ForumCheck.IsForumModerated(ForumGuid, Guid.Empty)

                'Set Default Sort Order and Direction
                Me.sortCriteria = "created"
                Me.sortDir = "asc"
                SetViewed(TopicGuid, False)
                LoadPage()
            End If

            ConfigBaseNavCtrls()

            If Me.Page.IsPostBack = False Then
                BuildBreadCrumbs()
                BindDataItems()
            End If

            If IsUserAuthenticated() Then
                Me.uxAddReplyButton.Visible = IsAllowed()
                Me.uxQuickReplyPanel.Visible = IsAllowed()
                Me.uxDeleteTopicButton.Visible = IsModerator()
                Me.uxMoveTopicButton.Visible = IsModerator()
                Me.uxFormumDropDownList.Visible = IsModerator()
            Else
                Me.uxAddReplyButton.Visible = False
                Me.uxQuickReplyPanel.Visible = False
                Me.uxDeleteTopicButton.Visible = False
                Me.uxMoveTopicButton.Visible = False
                Me.uxFormumDropDownList.Visible = False
			End If

			If ForumModerated Then
				Me.uxStatusLabel.Text = Resources.Resource.ForumModerated
			End If

        Else
            Me.uxPostPanel.Visible = False
            Me.uxPostPanel.Enabled = False
        End If

    End Sub

#End Region

#Region " Save Data "

#End Region

#Region " Load Data "

    Private Sub LoadPage()
        LoadPageSize(Me.uxPageSizeDropDownList)
        LoadForumList(Me.uxFormumDropDownList, ForumGuid.ToString().Trim())
    End Sub

    Private Sub BuildBreadCrumbs()

        Dim List As New TopicList
        Dim DT As New DataTable

        DT = List.GetBreadCrumbLinks(TopicGuid)

        With Me.uxBreadCrumbsRepeater
            .DataSource = DT
            .DataBind()
        End With

        Dim DR As DataRow

        For Each DR In DT.Rows
            TopicName = DR("topicname").ToString
        Next

    End Sub

    Public Overloads Overrides Sub BindDataItems()

        Dim List As New PostList
        Dim DT As New DataTable
        Dim DV As New DataView

        DT = List.GetPosts(TopicGuid)

        Me.RecordCount = DT.Rows.Count

        DV.Table = DT

        DV.Sort = Me.sortCriteria & " " & Me.sortDir

        If GetIntegerFromSession("page") > 0 Then
            Me.PageNumber = GetIntegerFromSession("page")
            Session.Add("page", 0) 'Clears the last page from session, since it is no longer needed
        End If

        Me.DataPage.DataSource = DV
        Me.DataPage.AllowPaging = True
        Me.DataPage.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.DataPage.CurrentPageIndex = Me.PageNumber

        CreatePagingLinks()

        With Me.uxPostRepeater
            .DataSource = Me.DataPage
            .DataBind()
        End With

    End Sub

#End Region

#Region " Form Controls Events "

    Protected Sub LoadBoards(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_board"))
    End Sub

    Protected Sub LoadCategories(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_category&categoryid={0}", e.CommandArgument.ToString))
    End Sub

    Protected Sub LoadForums(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_topic&forumid={0}", e.CommandArgument.ToString))
    End Sub

    Protected Sub DeleteTopic(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim Item As Topic = Topic.GetTopic(TopicGuid)

        SendPrivateMessage(Item.UserID, CurrentUserID, "Topic Deleted", "Your forum topic has been deleted.  Reasons could include inappropriate content, copyrighted material, or other possible reasons.")

        Topic.DeleteTopic(TopicGuid)
        Response.Redirect(String.Format("forum.aspx?pid=for_topic&forumid={0}", ForumGuid))
    End Sub

    Protected Sub AddPost(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_addpost&topicid={0}&page={1}", TopicGuid, Me.PageNumber))
    End Sub

    Protected Sub EditPost(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_addpost&topicid={0}&postid={1}&editpost=1&page={2}", TopicGuid, e.CommandArgument.ToString, Me.PageNumber))
    End Sub

    Protected Sub DenyPost(ByVal sender As Object, ByVal e As CommandEventArgs)

        Dim Item As Post = Post.GetPost(ConvertToGuid(e.CommandArgument.ToString().Trim()))

        Item.IsApproved = False
        Item.Save()

        SendPrivateMessage(Item.UserID, CurrentUserID, "Post Denied", "Your forum post has been denied.  Reasons could include inappropriate content, copyrighted material, or other possible reasons.")

        BindDataItems()

    End Sub

    Protected Sub DeletePost(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim Item As Post = Post.GetPost(ConvertToGuid(e.CommandArgument.ToString().Trim()))

        SendPrivateMessage(Item.UserID, CurrentUserID, "Post Deleted", "Your forum post has been deleted.  Reasons could include inappropriate content, copyrighted material, or other possible reasons.")

        Post.DeletePost(ConvertToGuid(e.CommandArgument.ToString().Trim()))

        BindDataItems()

    End Sub

    Protected Sub AttachItem(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_addpost&topicid={0}&postid={1}&editpost=1&attachitem=1&page={2}", TopicGuid, e.CommandArgument.ToString, Me.PageNumber))
    End Sub

    Protected Sub QuotePost(ByVal sender As Object, ByVal e As CommandEventArgs)
        Response.Redirect(String.Format("forum.aspx?pid=for_addpost&topicid={0}&postid={1}&quote=1&page={2}", TopicGuid, e.CommandArgument.ToString, Me.PageNumber))
    End Sub

    Protected Sub uxSaveButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxSaveButton.Click
        Dim Item As Post = Post.NewPost

        If Page.IsValid Then
            Item.PostBody = Replace(Me.uxQuickReplyTextbox.Text, vbCrLf, "<br />")
            Item.UserID = CurrentUserID
            Item.TopicID = TopicGuid
			If IsModerator() And ForumModerated Then
				Item.IsApproved = True
			Else
				Item.IsApproved = Not ForumModerated
			End If
            Item.Save()
        End If

        BindDataItems()

        Me.uxQuickReplyTextbox.Text = String.Empty

    End Sub

    Protected Sub uxMoveTopicButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uxMoveTopicButton.Click
        Dim Item As Topic = Topic.GetTopic(TopicGuid)

        Item.ForumID = ConvertToGuid(Me.uxFormumDropDownList)
        Item.Save()

        Response.Redirect(String.Format("forum.aspx?pid=for_post&topicid={0}&forumid={1}", TopicGuid, ConvertToGuid(Me.uxFormumDropDownList)))
    End Sub

    Protected Sub uxPostRepeater_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles uxPostRepeater.ItemDataBound
        Dim item As RepeaterItem = e.Item

        If (item.ItemType = ListItemType.Item) OrElse (item.ItemType = ListItemType.AlternatingItem) Then

            Dim Btn As Button = CType(item.FindControl("uxEditButton"), Button)
            Dim AttachBtn As Button = CType(item.FindControl("uxAttachButton"), Button)
            Dim Lbl As Label = CType(item.FindControl("uxEditedLabel"), Label)
            Dim Img As Image = CType(item.FindControl("uxAvatarImage"), Image)
            Dim Rpt As Repeater = CType(item.FindControl("uxAttachmentsRepeater"), Repeater)
            Dim LblSig As Label = CType(item.FindControl("uxSignatureLabel"), Label)
            Dim LblPost As Label = CType(item.FindControl("uxPostBodyLabel"), Label)
            Dim LblRank As Label = CType(item.FindControl("uxUserRankLabel"), Label)
            Dim ImgLevel As Image = CType(item.FindControl("uxUserLevelImage"), Image)

            If ShowItem(ConvertToGuid(e.Item.DataItem("ForumID").ToString)) = True Then

                Dim List As New ResourceList
                Dim DT As New DataTable

                DT = List.GetResourceListByItem(ConvertToGuid(item.DataItem("PostID").ToString)).Tables(0)

                If DT.Rows.Count > 0 Then
                    With Rpt
                        .DataSource = DT
                        .DataBind()
                    End With
                Else
                    Rpt.Visible = False
                End If

                If Not (item.DataItem("created").ToString.Trim.Equals(item.DataItem("edited").ToString.Trim)) Then
                    Lbl.Text = String.Format(" {0}", FormatLongEditDate(item.DataItem("edited").ToString.Trim))
                End If

                If IsUserAuthenticated Then
                    Btn.Visible = item.DataItem("userid").ToString.Trim.Equals(CurrentUserID.ToString.Trim) Or IsModerator()
                    AttachBtn.Visible = item.DataItem("userid").ToString.Trim.Equals(CurrentUserID.ToString.Trim) Or IsModerator()
                Else
                    Btn.Visible = False
                    AttachBtn.Visible = False
                End If

                If CType(item.DataItem("locked").ToString, Boolean) Then
                    ForumLocked = True
                Else
                    ForumLocked = False
                End If

                If EnableSmilies Then
                    LoadSmilies(LblPost, CurrentUser, item.DataItem("Post").ToString.Trim)
                Else
                    LblPost.Text = item.DataItem("Post").ToString.Trim
                End If

                LoadAvatar(Img, UserName(item.DataItem("userid").ToString().Trim()), False)
                LoadSignature(LblSig, UserName(item.DataItem("userid").ToString().Trim()))
                LoadUserRank(LblRank, item.DataItem("userpostcount").ToString)
                LoadUserLevel(ImgLevel, UserName(item.DataItem("userid").ToString().Trim()))

            Else
                e.Item.Visible = False
            End If

        End If
    End Sub

#End Region

#Region " Helpers and Methods "

    Protected Function IsAllowed() As Boolean
        Return (Not ForumLocked) Or IsModerator()
    End Function

    Protected Sub GetQueryStringValues()
        TopicGuid = GetGuidFromQueryString("topicid")
        ForumGuid = GetGuidFromQueryString("forumid")
    End Sub

    Private Sub ConfigBaseNavCtrls()

        Me.PagingTopPanel = Me.uxPagingTopPanel
        Me.PagingBottomPanel = Me.uxPagingBottomPanel

        Me.RepeaterTop = Me.uxPagesTopRepeater
        Me.RepeaterBottom = Me.uxPagesBottomRepeater

        Me.NextTopLinkButton = Me.uxTopNextLinkButton
        Me.PreviousTopLinkButton = Me.uxTopPrevLinkButton
        Me.NextBottomLinkButton = Me.uxBottomNextLinkButton
        Me.PreviousBottomLinkButton = Me.uxBottomPrevLinkButton

        Me.DataPage = DataPageLocal
        Me.PageSize = CType(Me.uxPageSizeDropDownList.SelectedValue.ToString, Integer)
        Me.PagesToDisplay = 10

        Me.ItemsPerPageDropDown = Me.uxPageSizeDropDownList
        Me.ItemsPerPageLabel = Me.uxItemsPerPageLabel
        Me.PagerInfoLabel = Me.uxPagerInfoLabel

        AddHandler Me.RepeaterTop.ItemCommand, AddressOf PagingRepeater_ItemCommand
        AddHandler Me.RepeaterBottom.ItemCommand, AddressOf PagingRepeater_ItemCommand

    End Sub

    Private Sub LoadSignature(ByVal Ctl As Label, ByVal User As String)

        If String.IsNullOrEmpty(Profile.GetProfile(User).UI.Signature) Then
            Ctl.Visible = False
        Else
            Ctl.Text = String.Format("<br /><hr>{0}<br />", Profile.GetProfile(User).UI.Signature.Trim)
        End If

    End Sub

    Private Sub LoadUserRank(ByVal Ctl As Label, ByVal PostCount As String)

        Dim Count As Int64 = Convert.ToInt64(PostCount.Trim)

        If Count <= 0 Then
            Ctl.Text = Resources.Resource.UserRanksNewbie
            Exit Sub
        End If
        If Count <= 5 Then
            Ctl.Text = Resources.Resource.UserRankMember
            Exit Sub
        End If
        If Count <= 50 Then
            Ctl.Text = Resources.Resource.UserRanksRegular
            Exit Sub
        End If
        If Count <= 100 Then
            Ctl.Text = Resources.Resource.UserRanksVeteran
            Exit Sub
        End If
        If Count <= 300 Then
            Ctl.Text = Resources.Resource.UserRanksExtreme
            Exit Sub
        End If
        If Count <= 600 Then
            Ctl.Text = Resources.Resource.UserRanksElite
            Exit Sub
        End If
        If Count > 601 Then
            Ctl.Text = Resources.Resource.UserRanksExpert
            Exit Sub
        End If

    End Sub

    Private Sub LoadUserLevel(ByVal Ctl As Image, ByVal UserName As String)

        If Roles.IsUserInRole(UserName, "admin") Then
            Ctl.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/admin.gif", Page.Theme.ToString.Trim)
        ElseIf Roles.IsUserInRole(UserName, "moderator") Then
            Ctl.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/moderator.gif", Page.Theme.ToString.Trim)
        Else
            Ctl.ImageUrl = String.Format("~/App_Themes/{0}/images/icons/member.gif", Page.Theme.ToString.Trim)
        End If

    End Sub

    Private Sub ConfigBaseEditorCtrls()
        'Me.FTBEditor = Me.uxQuickReplyTextbox
    End Sub

#End Region

End Class
